package common.library.utils;

import android.hardware.Camera;

import java.util.List;

import common.library.models.Size;
import lombok.var;

public class SizeUtil {

    public static Size ratioExtend(Size sourceSize, Size extendSize) {
        if (sourceSize.width < extendSize.width) {
            sourceSize.height = (int) (extendSize.width / (float) sourceSize.width * sourceSize.height);
            sourceSize.width = extendSize.width;
        }
        if (sourceSize.height < extendSize.height) {
            sourceSize.width = (int) (extendSize.height / (float) sourceSize.height * sourceSize.width);
            sourceSize.height = extendSize.height;
        }
        return sourceSize;
    }

    public static Size[] convert(List<Camera.Size> cameraSizes) {
        var sizes = new Size[cameraSizes.size()];
        for (int index = 0; index < sizes.length; index++)
            sizes[index] = new Size(cameraSizes.get(index));
        return sizes;
    }

    public static Size[] convert(android.util.Size[] utilSizes) {
        var sizes = new Size[utilSizes.length];
        for (int index = 0; index < sizes.length; index++)
            sizes[index] = new Size(utilSizes[index]);
        return sizes;
    }

    public static Size getMax(Size[] sizes) {
        var value = 0;
        var maxValue = 0;
        var maxSize = new Size();
        for (var size : sizes) {
            LogUtil.info("Getting max size from ({},{})", size.width, size.height);
            value = size.width * size.height;
            if (value > maxValue) {
                maxValue = value;
                maxSize = size;
            }
        }
        return maxSize;
    }

    public static Size getMatch(Size[] sizes, Size match) {
        var value = 0;
        var minValue = Integer.MAX_VALUE;
        var matchSize = new Size();
        for (var size : sizes) {
            LogUtil.info("Getting match size of ({},{}) from ({},{})", match.width, match.height, size.width, size.height);
            value = Math.abs(size.width - match.width) + Math.abs(size.height - match.height);
            if (value < minValue) {
                minValue = value;
                matchSize = size;
            }
        }
        return matchSize;
    }
}
